package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Address;
import com.dropdb.demo.bean.AddressExample;
import com.dropdb.demo.bean.Region;
import com.dropdb.demo.bean.RegionExample;
import com.dropdb.demo.bean.bo.BaseData;
import com.dropdb.demo.mapper.AddressMapper;
import com.dropdb.demo.mapper.RegionMapper;
import com.dropdb.demo.service.AddressService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author:tanxin Desc:
 * @date:2020/6/26 20:17
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Resource
    AddressMapper addressMapper;
    @Resource
    RegionMapper regionMapper;
    @Override
    public BaseData queryAddress(Integer page, Integer limit, String sort, String order,Integer userId,String name) {

        AddressExample addressExample = new AddressExample();
        //省份，市区，县
        RegionExample regionExample = new RegionExample();

        //条件查询
        if (userId != null && name != null) {
           addressExample.createCriteria().andNameEqualTo(name).andUserIdEqualTo(userId);
        }else if (userId != null) {
            addressExample.createCriteria().andUserIdEqualTo(userId);
        }else if (name != null) {
            addressExample.createCriteria().andNameEqualTo(name);
        }
        addressExample.setOrderByClause(sort + " " +order);
        PageHelper.startPage(page,limit);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        List<Region> regions = regionMapper.selectByExample(regionExample);
        //收货地址拼接
        for (Address address : addresses) {
            for (Region region : regions) {
                if (region.getId().equals(address.getProvinceId())){
                   address.setProvince(region.getName());
                }
                if (region.getId().equals(address.getCityId())){
                   address.setCity(region.getName());
                }
                if (region.getId().equals(address.getAreaId())){
                   address.setArea(region.getName());
                }
            }
        }
        PageInfo<Address> addressPageInfo = new PageInfo<>(addresses);
        long total = addressPageInfo.getTotal();
        return new BaseData(total,addresses);
    }
}
